﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AB_SD_Entities;
using System.Data.SqlClient;
using System.Data;
using AB_SD_Commons.Helpers;

namespace AB_SD_DataAccess
{
    public static class TownDAO
    {
        /// <summary>
        /// Select a town by id
        /// </summary>
        /// <param name="id">town id</param>
        /// <returns></returns>
        public static Town Select(int id)
        {
            Town result = new Town();

            string sql = "select * from town where id=@townid";
            SqlParameter[] sqlparams = new SqlParameter[1];
            sqlparams[0] = new SqlParameter("@townid", SqlDbType.Int);
            sqlparams[0].Value = id;
            DataTable dt = SqlHelper.ExecuteSelectQuery(sql, sqlparams);

            if (dt != null)
            {
                if (dt.Rows.Count == 1)
                {
                    result.Id = (int)dt.Rows[0]["Id"];
                    result.Name = dt.Rows[0]["Name"].ToString();
                    result.CountyId = (int)dt.Rows[0]["CountyId"];                    
                    return result;
                }
                else
                    return null;
            }
            else
                return null;            
        }

        /// <summary>
        /// Select all addresses in a town
        /// </summary>
        /// <param name="townID">town id</param>
        /// <returns></returns>
        public static List<Address> SelectAllAddresses(int townID)
        {
            List<Address> result = new List<Address>();

            string sql = "select Address.Id, Address.Postcode, Address.Address, Address.TownId "
            + "from (Address join Town on Address.TownId = Town.Id) "
            + "where Address.TownId = @townid";

            SqlParameter[] sqlParam = new SqlParameter[1];

            sqlParam[0] = new SqlParameter("@townid", SqlDbType.Int);
            sqlParam[0].Value = townID;

            DataTable dt = SqlHelper.ExecuteSelectQuery(sql, sqlParam);
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {

                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        Address address = new Address((int)dt.Rows[i]["Id"], dt.Rows[i]["Postcode"].ToString(), dt.Rows[i]["Address"].ToString(), (int)dt.Rows[i]["TownId"]);
                        result.Add(address);
                    }
                }
            }
            return result;
        }
    }
}
